// pages/listinfo/addNew/addNew.js
const app = getApp();
const WXAPI = require('../main/main')
var dateTimePicker = require('../../utils/DateUtil.js');
var TOOL = require('../../utils/util.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    backgroundColor: app.globalData.currentBgColor,//皮肤颜色
    StatusBar: 20,//遵循cu-custom的设置，与系统无关
    CustomBar: 74,//遵循cu-custom的设置，与系统无关
    SystemHeight: app.globalData.SystemHeight,//系统可用高度
    SystemWidth: app.globalData.SystemWidth,//系统可用宽度
    ScreenHeight: app.globalData.ScreenHeight,//系统宽度
    StatusBarHeight: app.globalData.StatusBarHeight,//状态宽度
    TabBarHeight: 50,
    loadModal:false,
    modalName: null,//弹出框名称

    /**地区选择**/
    Region: ['甘肃省', '兰州市', '城关区'],//地区数组
    Code: ["620000", "620100", "620102"],//区域代码
    /**单列选择**/
    singleSelectIndex: null,//单列选择索引
    singleSelect: ['九阳真经', '降龙十八掌', '如来神掌'],//单列选择值
    /**三列联动选择框**/
    multiArray: [['金庸', '古龙'],//第一列值数组
    ['雪山飞狐', '连城诀', '天龙八部', '笑傲江湖'],//金庸代表作【第一列第一个值对应的数组】
    ['胡一刀', '苗人凤', '田归农', '']//雪山飞狐对应英雄
    ],//三列联动选择框
    multiIndex: [0, 0, 0],//三列联动选择框索引
    /**仅时分选择**/
    time: '12:01',
    /**日期选择器**/
    date: '2018-12-25',
    /**具体时间选择框**/
    startYear: 2000,//开始时间
    endYear: 2050,//结束时间
    dateTimeArray: null,//选择框各列值数组
    dateTime: null,//选择时间数组的索引
    relTime: '',//选择后具体时间值（可使用的 yyyy-MM-dd HH:mm:ss）
    /**自定义多选样式**/
    selfCheckValue: [
                {value: 0,name: '西游记',checked: false,}, {value: 1,name: '红楼梦',checked: true,},
                {value: 2,name: '水浒传',checked: false,}, {value: 3,name: '三国演义',checked: false,}, 
                {value: 4, name: '无', checked: false,}, 
              ],
    /**图片上传**/
    FileList: [],//文件上传列表


     /***************关联选择*********** */
     assetList: [],//关联选择的所有数据
     selectedAssetList: [],//选中的数据
     selectAssetIdTemp: [],//选中的数据id
     Nomore: 'none',
     Loadmore: 'block',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    that.setDefaultDateTime();//设置默认具体时间
    that.getAssetList();
  },

  /**
   * 地址选择方法
   */
  getRegion: function (e) {
    console.log(e);
    this.setData({
      Region: e.detail.value,
      Code: e.detail.code
    })
  },

  /**
   * 单列选择器改变方法
   */
  singleSelectChange(e) {
    console.log(e);
    this.setData({
      singleSelectIndex: e.detail.value
    })
  },

  /***
   * 三列联动选择框设置值方法
   */
  MultiChange(e) {
    this.setData({
      multiIndex: e.detail.value
    })
  },
  /***
 * 三列联动选择框联动实现方法
 */
  MultiColumnChange(e) {
    let data = {
      multiArray: this.data.multiArray,
      multiIndex: this.data.multiIndex
    };
    data.multiIndex[e.detail.column] = e.detail.value;
    switch (e.detail.column) {
      //第一列值改变
      case 0:
        switch (data.multiIndex[0]) {
          case 0:
            //case 0: 金庸小说
            data.multiArray[1] = ['雪山飞狐', '连城诀', '天龙八部', '笑傲江湖'],//金庸代表作【第一列第一个值对应的数组】
              data.multiArray[2] = ['胡一刀', '苗人凤', '田归农', '']//雪山飞狐对应英雄
            break;

          case 1:
            //case 1: 古龙小说
            data.multiArray[1] = ['绝代双骄', '萧十一郎', '流星·蝴蝶·剑']
            data.multiArray[2] = ['小鱼儿', '花无缺', '邀月', '怜星'];
            break;
        }
        data.multiIndex[1] = 0;
        data.multiIndex[2] = 0;
        break;

      //第二列值改变
      case 1:
        switch (data.multiIndex[0]) {
          //case 0: 金庸小说
          case 0:
            switch (data.multiIndex[1]) {
              //雪山飞狐
              case 0:
                data.multiArray[2] = ['胡一刀', '苗人凤', '田归农', '']//雪山飞狐对应英雄
                break;

              //连城诀
              case 1:
                data.multiArray[2] = ['狄云', '水笙', '血刀老祖'];//连城诀对应英雄
                break;
              //天龙八部
              case 2:
                data.multiArray[2] = ['乔峰', '段誉', '虚竹'];//天龙八部对应英雄
                break;
              //笑傲江湖
              case 3:
                data.multiArray[2] = ['令狐冲', '任盈盈', '东方不败', '任我行']; //笑傲江湖对应英雄
                break;
            }
            break;

          //case 1: 古龙小说
          case 1:
            switch (data.multiIndex[1]) {

              //绝代双骄
              case 0:
                data.multiArray[2] = ['小鱼儿', '花无缺', '邀月', '怜星'];//绝代双骄对应英雄
                break;
              //萧十一郎
              case 1:
                data.multiArray[2] = ['萧十一郎', '沈碧君', '逍遥侯'];//萧十一郎对应英雄
                break;
              //流星·蝴蝶·剑
              case 2:
                data.multiArray[2] = ['孟星魂', '小蝶', '孙玉伯'];
                break;
            }
            break;
        }
        data.multiIndex[2] = 0;
        break;
    }
    this.setData(data);
  },

  //时分选择器
  TimeChange(e) {
    this.setData({
      time: e.detail.value
    })
  },

  //日期选择器
  DateChange(e) {
    this.setData({
      date: e.detail.value
    })
  },

  /**设置具体时间选择器页面加载默认值**/
  setDefaultDateTime() {
    // 获取完整的年月日 时分秒，以及默认显示的数组
    var obj = dateTimePicker.dateTimePicker(this.data.startYear, this.data.endYear);
    var dateArr = obj.dateTimeArray;
    var timeIndex = obj.dateTime;
    this.setData({
      dateTimeArray: obj.dateTimeArray,
      dateTime: obj.dateTime,
      relTime: dateArr[0][timeIndex[0]] + '-' + dateArr[1][timeIndex[1]] + '-' + dateArr[2][timeIndex[2]]
        + ' ' + dateArr[3][timeIndex[3]] + ':' + dateArr[4][timeIndex[4]] + ':' + dateArr[5][timeIndex[5]],
    });
  },
  /**具体时间选择框值改变事件**/
  changeDateTime(e) {
    var arr = this.data.dateTime, dateArr = this.data.dateTimeArray;
    var timeIndex = this.data.dateTime;
    this.setData({
      dateTime: e.detail.value,
      relTime: dateArr[0][timeIndex[0]] + '-' + dateArr[1][timeIndex[1]] + '-' + dateArr[2][timeIndex[2]]
        + ' ' + dateArr[3][timeIndex[3]] + ':' + dateArr[4][timeIndex[4]] + ':' + dateArr[5][timeIndex[5]],
    });
  },

  /**具体时间列改变事件**/
  changeDateTimeColumn(e) {
    var arr = this.data.dateTime, dateArr = this.data.dateTimeArray;
    arr[e.detail.column] = e.detail.value;
    dateArr[2] = dateTimePicker.getMonthDay(dateArr[0][arr[0]], dateArr[1][arr[1]]);
    this.setData({
      dateTimeArray: dateArr,
      dateTime: arr,
    });
  },
  /**自定义选择检查选中值事件**/
  ChooseCheckbox(e) {
    let items = this.data.selfCheckValue;
    let values = e.currentTarget.dataset.value;
    /**当选择无  清除其它选项**/
    if (values == 4) { 
      for (let i = 0, lenI = items.length; i < lenI; ++i) {
        if (items[i].checked) {
          items[i].checked = !items[i].checked;
        }
        if (items[i].value == values) {
          items[4].checked = true;
          break
        }
      }
    } else {
      items[4].checked = false;
      for (let i = 0, lenI = items.length; i < lenI-1; ++i) {
        if (items[i].value == values) {
          items[i].checked = !items[i].checked;
          break
        }
      }
    }
    this.setData({
      selfCheckValue: items
    })
  },


  /**图片上传选择图片**/
  ChooseImage() {
    wx.chooseImage({
      count: 4, //默认9
      sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], //从相册选择
      /**图片选择成功回调函数**/
      success: (res) => {
        if (this.data.FileList.length != 0) {
          this.setData({
            FileList: this.data.FileList.concat(res.tempFilePaths)
          })
        } else {
          this.setData({
            FileList: res.tempFilePaths
          })
        }
      },
      /**图片选择失败回调函数**/
      fail: (res) => {
        console.log("图片选择失败，错误如下:");
        console.log(res);
      },
      /**接口调用结束的回调函数（调用成功、失败都会执行）**/
      complete: (res) => {

      },
    });
  },
  /**选择图片点击预览的图**/
  ViewImage(e) {
    wx.previewImage({
      urls: this.data.FileList,
      current: e.currentTarget.dataset.url
    });
  },
  /**点击X去清楚当前的图片文件**/
  DelImg(e) {
    this.data.FileList.splice(e.currentTarget.dataset.index, 1);
    this.setData({
      FileList: this.data.FileList
    });
  },
/**返回按钮事件**/
  doBack(){
    TOOL.doBack();
  },
  /****
   * @funtction 提交数据事件
   */
  doSubmit(e){
     var that=this;
     that.setData({
       loadModal:true
     })
  },
  /***
   *显示弹出框
   */
  showModal: function (e) {
    var name = e.currentTarget.dataset['name'];//所带名称参数 
    this.setData({
      modalName: name
    })
  },
  /***
     *隐藏弹出框
     */
  hideModal: function () {
    this.setData({
      modalName: null
    })
  },

  /****
   * 搜索资产
   * **/
  searchAsset: function (e) {
    var that = this;
    var assetName = e.detail.value;
    console.log(assetName);
    var newAssetArr = that.data.assetList;
    for (var i = 0; i < newAssetArr.length; i++) {
      newAssetArr[i].isShow = true;
      if (newAssetArr[i].assetname.indexOf(assetName.trim()) < 0) {
        newAssetArr[i].isShow = false;
      }
    };
    that.setData({
      assetList: newAssetArr,
    })

  },
  /****
  * 加载关联选择数据
  * **/
  getAssetList() {
    var that = this;
    /**********************加载************************/
    // WXAPI.getAssetListByProject({
    //   project: projectId,
    //   // 接口调用获取列表
    // }).then(function (res) {
    //   console.log("============资产列表请求数据============");
    //   console.log(res);
    //   if (res.code == 200 && res.msg == "success") {
    //     var newstr = JSON.stringify(res);
    //     var jsarr = JSON.parse(newstr);
    //     for (var i = 0; i < jsarr.rows.length; i++) {
    //       if(assetId == jsarr.rows[i].id){
    //         jsarr.rows[i].isCheck = true;
    //       }else{
    //         jsarr.rows[i].isCheck = false;
    //       }
    //       jsarr.rows[i].isShow = true;
    //     }
    //     that.setData({
    //       assetList: that.data.assetList.concat(jsarr.rows),
    //       Nomore: 'block',
    //       Loadmore: 'none',
    //     });
    //   } else {
    //     TOOL.showErrorToast("服务器运行出错，请联系管理员！");
    //     return;
    //   }
    // });
    that.setData({
      assetList:[{
        //业务数据
        assetCode: "ZC202006160022",
        assetCount: 1,
        assetname: "测试资产-001",
        assetstate: "2510000000420112",
        assetstateName: "在库损坏",
        assettype: "2510000000420096",
        assettypeName: "机架式服务器",
        createGroupId: "123",
        createTime: "2020-06-16 15:54:19",
        createUser: "测试001",
        createUserId: "23",
        id: "722479179395895296",
        maintenancesupplier: "赤川信息技术有限公司",
        model: "萨法",
        project: "722477398909652992",
        projectName: "测试002",
        repairphonenumber: "15111111111",
        spec: "阿斯旺嗡嗡嗡",
        unit: "59",
        unitName: "件",
        updateTime: "2020-06-18 15:06:39",
        //额外添加字段
        isCheck:false,
        isShow:true,
      },{
        //业务数据
        assetCode: "ZC202006160022",
        assetCount: 1,
        assetname: "测试资产-001",
        assetstate: "2510000000420112",
        assetstateName: "在库损坏",
        assettype: "2510000000420096",
        assettypeName: "机架式服务器",
        createGroupId: "123",
        createTime: "2020-06-16 15:54:19",
        createUser: "测试001",
        createUserId: "23",
        id: "722479179395895296",
        maintenancesupplier: "赤川信息技术有限公司",
        model: "萨法",
        project: "722477398909652992",
        projectName: "测试002",
        repairphonenumber: "15111111111",
        spec: "阿斯旺嗡嗡嗡",
        unit: "59",
        unitName: "件",
        updateTime: "2020-06-18 15:06:39",
        //额外添加字段
        isCheck:false,
        isShow:true,
      },{
        //业务数据
        assetCode: "ZC202006160022",
        assetCount: 1,
        assetname: "测试资产-001",
        assetstate: "2510000000420112",
        assetstateName: "在库损坏",
        assettype: "2510000000420096",
        assettypeName: "机架式服务器",
        createGroupId: "123",
        createTime: "2020-06-16 15:54:19",
        createUser: "测试001",
        createUserId: "23",
        id: "722479179395895296",
        maintenancesupplier: "赤川信息技术有限公司",
        model: "萨法",
        project: "722477398909652992",
        projectName: "测试002",
        repairphonenumber: "15111111111",
        spec: "阿斯旺嗡嗡嗡",
        unit: "59",
        unitName: "件",
        updateTime: "2020-06-18 15:06:39",
        //额外添加字段
        isCheck:false,
        isShow:true,
      },{
        //业务数据
        assetCode: "ZC202006160022",
        assetCount: 1,
        assetname: "测试资产-001",
        assetstate: "2510000000420112",
        assetstateName: "在库损坏",
        assettype: "2510000000420096",
        assettypeName: "机架式服务器",
        createGroupId: "123",
        createTime: "2020-06-16 15:54:19",
        createUser: "测试001",
        createUserId: "23",
        id: "722479179395895296",
        maintenancesupplier: "赤川信息技术有限公司",
        model: "萨法",
        project: "722477398909652945",
        projectName: "测试002",
        repairphonenumber: "15111111111",
        spec: "阿斯旺嗡嗡嗡",
        unit: "59",
        unitName: "件",
        updateTime: "2020-06-18 15:06:39",
        //额外添加字段
        isCheck:false,
        isShow:true,
      },{
        //业务数据
        assetCode: "ZC202006160022",
        assetCount: 1,
        assetname: "测试资产-001",
        assetstate: "2510000000420112",
        assetstateName: "在库损坏",
        assettype: "2510000000420096",
        assettypeName: "机架式服务器",
        createGroupId: "123",
        createTime: "2020-06-16 15:54:19",
        createUser: "测试001",
        createUserId: "23",
        id: "72247917939589523",
        maintenancesupplier: "赤川信息技术有限公司",
        model: "萨法",
        project: "722477398909652923",
        projectName: "测试002",
        repairphonenumber: "15111111111",
        spec: "阿斯旺嗡嗡嗡",
        unit: "59",
        unitName: "件",
        updateTime: "2020-06-18 15:06:39",
        //额外添加字段
        isCheck:false,
        isShow:true,
      },{
        //业务数据
        assetCode: "ZC202006160022",
        assetCount: 1,
        assetname: "测试资产-001",
        assetstate: "2510000000420112",
        assetstateName: "在库损坏",
        assettype: "2510000000420096",
        assettypeName: "机架式服务器",
        createGroupId: "123",
        createTime: "2020-06-16 15:54:19",
        createUser: "测试001",
        createUserId: "23",
        id: "722479179395895212",
        maintenancesupplier: "赤川信息技术有限公司",
        model: "萨法",
        project: "722477398909652992",
        projectName: "测试002",
        repairphonenumber: "15111111111",
        spec: "阿斯旺嗡嗡嗡",
        unit: "59",
        unitName: "件",
        updateTime: "2020-06-18 15:06:39",
        //额外添加字段
        isCheck:false,
        isShow:true,
      },{
        //业务数据
        assetCode: "ZC202006160022",
        assetCount: 1,
        assetname: "测试资产-001",
        assetstate: "2510000000420112",
        assetstateName: "在库损坏",
        assettype: "2510000000420096",
        assettypeName: "机架式服务器",
        createGroupId: "123",
        createTime: "2020-06-16 15:54:19",
        createUser: "测试001",
        createUserId: "23",
        id: "722479179395895292",
        maintenancesupplier: "赤川信息技术有限公司",
        model: "萨法",
        project: "722477398909652992",
        projectName: "测试002",
        repairphonenumber: "15111111111",
        spec: "阿斯旺嗡嗡嗡",
        unit: "59",
        unitName: "件",
        updateTime: "2020-06-18 15:06:39",
        //额外添加字段
        isCheck:false,
        isShow:true,
      }],
      Nomore: 'block',
      Loadmore: 'none'
    })
  },

  /*****
   * 选择关联资产
   */
  checkBoxChange: function (e) {
    var arrTemp = e.detail.value;
    console.log("============选中============");
    console.log(arrTemp);
    this.setData({
      selectAssetIdTemp: arrTemp
    })
  },

  /*****
   * 确认选择关联资产
   */
  confirmSelectAsset: function () {
    var that = this;
    var idStr = that.data.selectAssetIdTemp.join(",");
    var tempSelectedAsset = [];
    var assetListTemp = that.data.assetList;
    for (var i = 0; i < assetListTemp.length; i++) {
      if (idStr.indexOf(assetListTemp[i].id) > -1) {
        assetListTemp[i].isCheck = true;
        tempSelectedAsset.push({
          id: '',
          parentId: assetListTemp[i].id,//设置子表的parentId为原表Id
          itemNumber: assetListTemp[i].assetCode,
          name: assetListTemp[i].assetname,
          states: assetListTemp[i].assetstateName,
          sysname: assetListTemp[i].assettypeName,
        });
      }else{
        assetListTemp[i].isCheck = false;
      }
    }
    that.setData({
      assetList: assetListTemp,
      selectedAssetList: tempSelectedAsset,
      modalName: null,
    })
  },

  /***
   * 删除选中的关联资产
   */
  deleteSelectedAsset: function (e) {
    var that = this;
    console.log(e);
    var deleteId = e.currentTarget.dataset['deleteid'];
    console.log("=============删除已选中的关联资产-============");
    var selectedAssetListTemp = this.data.selectedAssetList.filter((item, index, arr) => item.parentId != deleteId);
    var assetListTemp = that.data.assetList;
    for (var i = 0; i < assetListTemp.length; i++) {
      if (assetListTemp[i].id == deleteId) {
        assetListTemp[i].isCheck = false;
      }
    }
    this.setData({
      assetList: assetListTemp,
      selectedAssetList: selectedAssetListTemp
    })
  },
})